/**
 * 
 */
package com.base.myproject.client.busi;


import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.base.myproject.client.busi.BO.BaseObject;
import com.base.myproject.client.busi.BO.BusiObject;
import com.base.myproject.client.busi.service.CcodeBusiObject;
import com.base.myproject.client.jdbc.StoreInfo;
import com.base.myproject.client.system.SystemMessage;
import com.base.myproject.client.tools.CommandFactory;
import com.base.myproject.client.tools.Debug;
import com.base.myproject.client.tools.SendServlet;
import com.extjs.gxt.ui.client.data.BasePagingLoadResult;
import com.extjs.gxt.ui.client.data.BasePagingLoader;
import com.extjs.gxt.ui.client.data.ChangeEvent;
import com.extjs.gxt.ui.client.data.ChangeEventSource;
import com.extjs.gxt.ui.client.data.DataField;
import com.extjs.gxt.ui.client.data.HttpProxy;
import com.extjs.gxt.ui.client.data.ListLoadResult;
import com.extjs.gxt.ui.client.data.ListLoader;
import com.extjs.gxt.ui.client.data.LoadEvent;
import com.extjs.gxt.ui.client.data.Model;
import com.extjs.gxt.ui.client.data.ModelData;
import com.extjs.gxt.ui.client.data.ModelType;
import com.extjs.gxt.ui.client.data.PagingLoadConfig;
import com.extjs.gxt.ui.client.data.PagingLoadResult;
import com.extjs.gxt.ui.client.data.PropertyChangeEvent;
import com.extjs.gxt.ui.client.data.XmlReader;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.event.LoadListener;
import com.extjs.gxt.ui.client.store.ListStore;
import com.extjs.gxt.ui.client.store.Record;
import com.extjs.gxt.ui.client.store.StoreEvent;
import com.extjs.gxt.ui.client.store.StoreListener;
import com.extjs.gxt.ui.client.store.Record.RecordUpdate;
import com.extjs.gxt.ui.client.util.Format;
import com.extjs.gxt.ui.client.util.Params;
import com.extjs.gxt.ui.client.widget.Info;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.extjs.gxt.ui.client.widget.toolbar.PagingToolBar;
import com.google.gwt.core.client.GWT;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;
import com.google.gwt.http.client.URL;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.xml.client.Document;
import com.google.gwt.xml.client.Element;
import com.google.gwt.xml.client.Node;
import com.google.gwt.xml.client.NodeList;
import com.google.gwt.xml.client.XMLParser;

/**
 * @author zgw
 * 
 * 
 */
public class BaseStore<M extends ModelData> extends ListStore<M> implements
		RequestCallback, BaseStoreListener {
	private Map<BaseStoreEvent.EventType, List> listeners;
	private BaseStore<ModelData> parent = null; // main store
	private ArrayList<BaseStore> chilestore = new ArrayList<BaseStore>(); // chile
	// list

	private String name = null;
	private int curcowindex = -1; // 当前所在行
	private String tablename = null;// 表表名
	private String[] keyname = null;// new String[] { "gcode" };// 主键
	String[] linkparentcolumns = null; // 与主表关联的字段 (主表字段)
	String[] linkparent_chile_columns = null;// 与主表关联的字段（子表字段） 子表与主表关联字段，用于子表添加记录的时候保持和主表内容一致
	//protected List<M> insertdata = new ArrayList<M>(); // 插入数据数量
	//protected List<M> deletedata = new ArrayList<M>(); // 删除数据
	String deletechilesql = "";// // 删除子表数据
	final String SAVE = "SAVE"; // ���͵������������¼�

	String servletresponeString = null; // ������ص��ַ�һ���ǳɹ����¼���

	StoreInfo storeinfo = null;
	BaseStore basestorethis = null;
	// 行增加的默认值
	java.util.HashMap<String, Object> defaultvalue = new java.util.HashMap<String, Object>();
	// 注册分页，到reload和load的时候注册他
	PagingToolBar pagingtoolBar = null;

	boolean iscompleted = false;

	final int READONLY = 1; // 可读
	final int WRITE_ENABLE = 2;// 可写
	final int DELETE_ENABLE = 4;// 可删除

	int basestorerwdstatus = 7;// 可读, 可写,可删除 3个值相加
	
	boolean needtodeelroweditable = false;
	
	ArrayList<Editdisable> editdisablelist = new ArrayList<Editdisable>();
	
	// 行被删除的比较信息，如果比较信息返回真就说明能够被删除
	java.util.LinkedList<RecordCompareInfo> recorddeletecomparell = new java.util.LinkedList<RecordCompareInfo>();
	// 行被增加的比较信息，如果比较信息返回真就说明能够被证件
	java.util.LinkedList<RecordCompareInfo> recordaddcomparell = new java.util.LinkedList<RecordCompareInfo>();

	// 自增字段，从服务器上取数的时候设置，客户端每次新增记录的时候在原值上加1
	protected String autoinc = "0";

	String totlerowcount;

	int mode = 1;// 模式，默认是用模式1，表示在loader里面用的是BusiObject,否则是BaseModel,以后可能还有更多的模式

	boolean ischanged = false;

	boolean needsave = true;//默认需要保存，
	
	
	String sqlnow = null; //当前basestore的sql，有可能为空
	/**
	 * @return the mode
	 */
	public int getMode() {
		return mode;
	}

	/**
	 * @param mode the mode to set
	 */
	public void setMode(int mode) {
		this.mode = mode;
	}

	public PagingToolBar getToolBar() {
		return pagingtoolBar;
	}

	public void setToolBar(PagingToolBar toolBar) {
		this.pagingtoolBar = toolBar;
	}

	public ArrayList<BaseStore> getChilestore() {
		return chilestore;

	}

	public void setChilestore(ArrayList<BaseStore> chilestore) {
		this.chilestore = chilestore;
	}

	public StoreInfo getStoreinfo() {
		return storeinfo;
	}

	public void setStoreinfo(StoreInfo storeinfo) {
		this.storeinfo = storeinfo;
		setTablename(storeinfo.getTablename());
		if (storeinfo.getKeyname() != null) {
			this.setKeyname(storeinfo.getKeyname());
		}
	}

	public String getServletresponeString() {
		return servletresponeString;
	}

	public void setServletresponeString(String servletresponeString) {
		this.servletresponeString = servletresponeString;
	}

	ModelType type = null;

	public ModelType getType() {
		return type;
	}

	public void setType(ModelType type) {
		this.type = type;
	}

	public String[] getKeyname() {
		return keyname;
	}

	public void setKeyname(String[] keyname) {
		this.keyname = keyname;
	}

	public String getTablename() {
		return tablename;
	}

	public void setTablename(String tablename) {
		this.tablename = tablename;
	}

	public int getCurcowindex() {
		return curcowindex;
	}

	public void setCurcowindex(int curcowindex) {
		this.curcowindex = curcowindex;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public BaseStore getParent() {
		return parent;
	}

	public void setParent(BaseStore parent) {
		this.parent = parent;
		this.parent.addChileStroe(this);

		parent.addBaseStoreListener(BaseStoreEvent.EventType.ROW_CHANGED, this);
		parent
				.addBaseStoreListener(BaseStoreEvent.EventType.SAVE_STARTED,
						this);
		parent.addBaseStoreListener(BaseStoreEvent.EventType.SAVE_COMPLETE,
				this);

	}

	public boolean isParent() {
		return chilestore.size() > 0;
	}

	public void addChileStroe(BaseStore bs) {
		chilestore.add(bs);
	}

	public BaseStore(ModelType type, StoreInfo storeinfo) {
		this(type, storeinfo, true);
	}

	/**
	 * 
	 * @param type
	 * @param storeinfo
	 * @param autoload
	 *            如果是true，自动读取（当然还有是否只父类等条件），否则，要调用load来读取数据
	 */
	boolean autoload = true;

	public BaseStore(ModelType type, StoreInfo storeinfo, boolean autoload) {
		this(type, storeinfo, autoload, 1);
	}

	public BaseStore(ModelType type, StoreInfo storeinfo, boolean autoload,
			int mode) {

		this();
		this.mode = mode;
		this.autoload = autoload;
		setType(type);
		setStoreinfo(storeinfo);

		// 如果是直接设置的方式自动读取记录
		initcompleted();
	}

	
	@SuppressWarnings("unchecked")
	public void initcompleted() {
		if (!iscompleted) {
			if (storeinfo.getParent() != null) {
				this.setParent(storeinfo.getParent());
			}
			if (storeinfo.getLinkparentcolumns() != null) {
				this.setLinkparentcolumns(storeinfo.getLinkparentcolumns());
				this.setLinkparent_chile_columns(storeinfo
						.getLinkparent_chile_columns());
			}

			this.addStoreListener(new StoreListener() {
				public void storeAdd(StoreEvent se) {
				}

				public void storeRemove(StoreEvent se) {

				}

				public void storeClear(StoreEvent se) {

				}

			});
			if (this.getParent() == null && autoload)
				load();
			iscompleted = true;

		}
	}

	public BaseStore() {
		super();
		basestorethis = this;
		this.addBaseStoreListener(BaseStoreEvent.EventType.ROW_CHANGED, this);
	}

	public BaseStore(BasePagingLoader loader) {
		this();
		this.loader = loader;
	}

	boolean isinit = false;
	/**
	 * 加载数据前装备，有些情况下只是做事件的处理，无必要从数据库读取数据。例如新增的时候，数据库本身一定无数据所以就没必要和服务器通信
	 */
	public void preload() {
		
		//默认情况下用的loader
		if (loader == null) {
			loader = (BasePagingLoader) getBaseLoader(getType(), getStoreinfo());

		}
		//zgw 20100906 bug 重新加载数据会重复添加事件
//		if(!isinit)
//		loader.removeAllListeners();
		
		if (getToolBar() != null) {

			getToolBar().bind((BasePagingLoader) loader);
		}
		if(!isinit)
		loader.addLoadListener(new LoadListener() {

			public void loaderBeforeLoad(LoadEvent le) {
				fireEvent(BaseStoreEvent.EventType.LOAD_STARTED, BaseStoreEvent
						.BaseStoreLOAD_STARTED(basestorethis));

				onBeforeLoad(le);
			}

			public void loaderLoad(LoadEvent le) {

				onLoad(le);


				//zgw 2010-11-18 为什么在没有父类的时候移动到第一行，有父类不移动？屏蔽?
				//if (basestorethis.getParent() == null) 
				{
					
					if (basestorethis.getCount() > 0)
						basestorethis.gotorow(0);
				}
			

				_LoadComplete();

			}

			public void loaderLoadException(LoadEvent le) {
				onLoadException(le);
			}

		});
		isinit = true;
	}
	/**
	 * load完成，触发事件，
	 * 有时候在本地添加，不需要从服务器端加载数据的时候，也需要手动调用
	 * _LoadComplete(),触发加载完成事件
	 */
	public void _LoadComplete()
	{
	
		fireEvent(BaseStoreEvent.EventType.LOAD_COMPLETE,
				BaseStoreEvent.BaseStoreLoadComplete(basestorethis));
	}

	public void load() {
		curcowindex = -1;
		preload();
		loader.load();
	}

	public Object getValue(int row, String name) {
		return this.getAt(row).get(name);

	}

	public Object getValue(String name) {
		if(curcowindex>-1)
			return getValue(curcowindex, name);
		else
		{
			return null;
			
		}
	}

	@Deprecated
	public Object getValue(int i) {
		return "zzz";
	}

	/**
	 * 被编辑前的值，如果未被编辑则返回当前值
	 * 
	 * @param row
	 * @param name
	 * @return
	 */
	public Object getValueBefoEdited(int row, String name) {

		if (this.getRecord(this.getAt(row)).isModified(name)) {
			return this.getRecord(this.getAt(row)).getChanges().get(name);
		}

		return getValue(row, name);
	}

	/**
	 * 当前行赋值
	 * 
	 * @param name
	 * @param value
	 */
	public void setValue(String name, Object value) {

		if (curcowindex == -1)
			throw new java.lang.RuntimeException("未找到指定的行");
		setValue(curcowindex, name, value);
	}

	/**
	 * 指定行赋值 needfireevent 为true则发送事件，否则不发送。通常情况下在做计算时，不进行事件发送，避免进入无限循环
	 * 
	 * @param index
	 * @param name
	 * @param value
	 * @param needfireevent
	 */
	public void setValue(int index, String name, Object value,
			boolean needfireevent) {


		Object oldvalue =this.getModels().get(index).get(name);
	
		
		this.getRecord(((M) this.getModels().get(index))).set(name, value,
				needfireevent);
		fireEvent(BaseStoreEvent.EventType.CELL_CHANGED, BaseStoreEvent
				.BaseStoreCellChanged(basestorethis, index, name));
		if((this.getModels().get(index)) instanceof Model)
		{
			GWT.log("notify...");
			Model md = (Model) this.getModels().get(index);
			ChangeEvent ce = new PropertyChangeEvent(ChangeEventSource.Update,md,name,oldvalue,value);
			md.notify(ce);
		}

	}

	public void setValue(int index, String name, Object value) {
		setValue(index, name, value, true);
	}

	/**
	 * 清除状态
	 * 
	 * @param index
	 */
	public void clearStatus(int index) {
		ModelData m = getAt(index);

		if (m instanceof BaseObject) {
			((BaseObject) m).clearBusistatus();
		}
	}

	/**
	 * 改变状态，在gridview中接收到了busistatus 状态的改变显示方式 同时
	 * store的添加，保存，删除，等都是根据status的值进行判断提交到服务器。trysave中做了处理。
	 * 
	 * @param index
	 * @param status
	 */
	public void setStatus(int index, int status) {
		ModelData m = getAt(index);
		setStatus(m, status);
	}

	public void setStatus(ModelData m, int status) {
		if (m instanceof BaseObject) {
			((BaseObject) m).setBusistatus(status);
			// update(m);
			fireStoreEvent(Update, RecordUpdate.EDIT, this.getRecord((M) m));
		}
	}
	
	/**
	 * 去除属性 @see BaseObject
	 * @param index
	 * @param status
	 */
	public void removeStatus(int index, int status) {
		ModelData m = getAt(index);
		removeStatus(m, status);
	}
	/**
	 * 去除属性 @see BaseObject
	 * @param index
	 * @param status
	 */
	public void removeStatus(ModelData m, int status) {
		if (m instanceof BaseObject) {
			((BaseObject) m).removeBusistatus(status);
			fireStoreEvent(Update, RecordUpdate.EDIT, this.getRecord((M) m));
		}
	}

	/**
	 * 跳转到某一行，通常情况下有grid触发，然后触发行改变的事件
	 * 
	 * @param index
	 * @return
	 */
	public ModelData gotorow(int index) {

		// 如果行没有发生改变不触发事件
		//if (curcowindex != index)  这句话被屏蔽是因为在做过滤的时候，光标如果都在第一行 就不会触发行改变，导致数据
		//（在form中）未能正常显示
		//打开，在grid里已经通过事件处理。
		//有bug 第一行时候有bug，事件不能触发，2010-10-16 改为第一行始终触发，以后要改为更好的方式，@TODO
		if (curcowindex != index ) 

		{
			
			curcowindex = index;
			
			this.fireEvent(BaseStoreEvent.EventType.ROW_CHANGED, BaseStoreEvent
					.BaseStoreRowChangedEvent(this, curcowindex));
		}
		return getAt(index);
	}

	/**
	 * 舍弃，因为如果是busiobject提供的信息不足，比如主键和表名等信息
	 */
	@Deprecated
	public void add() {
		HashMap hm = new HashMap();

		BaseObject modeldata = new BaseObject(hm);

		add((M) modeldata);
	}

	/**
	 * 加入的是BusiObject
	 */
	public void addX() {
		HashMap hm = new HashMap();

		BusiObject modeldata = new BusiObject(hm);

		add((M) modeldata);
	}

	/**
	 * TODO 有bug，请用 add(HashMap hm)
	 */
	public void add(M modeldata) {

		add(modeldata, true, true);

	}
	@SuppressWarnings("unchecked")
	public void add(HashMap hm)
	{
		BusiObject modeldata = new BusiObject(hm);
		add((M) modeldata);
	}


//	public void add( M modeldata, final boolean b, boolean forjdbc)
//
//	{
//		add(modeldata,b,forjdbc,null);
//	}
	
	/**
	 * 
	 * @param modeldata
	 * @param b
	 * @param forjdbc
	 *            true 为了数据库更新 ，否则不生成主码
	 * 
	 *            主码必须是icode，如果有不重复的约束条件那么会在添加多条记录的时候对话框提示
	 *
	 * si.addBusiParams("CODENAMEPARAMS", "{D:MMdd}{INC:3}{see}");
		si.addBusiParamshm.put("CODENAMEFILTER", "1=1");
		si.addBusiParamshm.put("CODENAME", "ccode");
	 */
	public void add( M modeldata, final boolean b, boolean forjdbc)

	{
		DateTimeFormat activeFormat = DateTimeFormat
		.getFormat("yyyy-M-d H:mm:ss");
		GWT.log("str3="+modeldata.getProperties());
		if (b) {
			if (modeldata == null) {
				HashMap hm = new HashMap();

				modeldata = (M) new BaseObject(hm);

			}
			for (String key : defaultvalue.keySet()) {
				if (modeldata.get(key) == null) {
					modeldata.set(key, defaultvalue.get(key));
				}
			}
			// 加入默认自增字段
			if (this.getStoreinfo() != null
					&& this.getStoreinfo().getAutoinccolumn() != null) {
				int inc = Integer.parseInt(this.getAutoinc()) + 1;
				this.setAutoinc(inc + "");

				modeldata.set(this.getStoreinfo().getAutoinccolumn(), "zgw"
						+ "_" + inc);
			}
			// 如果有父类，就要将关联字段
			if (getParent() != null) {
				// 在主子表设置的数组长度不一致的时候，会报数组越界的错误
				for (int i = 0; getLinkparent_chile_columns() !=null && i < getLinkparent_chile_columns().length ; i++) {
					//如果父类的关联字段是modeldata，那么就要取code做关联
					if(getParent().getValue(getLinkparentcolumns()[i]) instanceof ModelData)
					{
						modeldata.set(getLinkparent_chile_columns()[i], ((ModelData)getParent()
								.getValue(getLinkparentcolumns()[i])).get("code"));
					}
					else
					{
					
					modeldata.set(getLinkparent_chile_columns()[i], getParent()
							.getValue(getLinkparentcolumns()[i]));
					}
				}

			}
			if (modeldata instanceof JDBCModelData)
				((JDBCModelData) modeldata).setStatus(JDBCModelData.ROW_INSERT);// 行插入状态
		}
		if (modeldata instanceof BusiObject) {
			((BusiObject) modeldata).setStoreinfo(storeinfo);

		}
		if (modeldata instanceof BaseObject) {
			((BaseObject) modeldata).setBusistatus(BaseObject.INSERT);
		}
		// 向服务器索取icode
		if (forjdbc) {

			// 如果有父类，就要将关联字段,子表添加的时候，要将与主表关联的值也一起设置
			String columnname = "";
			String columnvalue = "";
			if (getParent() != null) {
				// 在主子表设置的数组长度不一致的时候，会报数组越界的错误
				for (int i = 0; i < getLinkparentcolumns().length; i++) {
					columnname += "" + getLinkparent_chile_columns()[i] + ",";
				
					if(getParent().getValue(getLinkparentcolumns()[i]) instanceof ModelData)
					{
					
						columnvalue += "'"
							+ ((ModelData)getParent()
									.getValue(getLinkparentcolumns()[i])).get("code")
							+ "',";
						
					}
				
					else if(getParent().getType()!=null && (getParent().getType().getField(getLinkparent_chile_columns()[i])!=null) && (getParent().getType().getField(getLinkparent_chile_columns()[i]).getType()!=null) &&
							getParent().getType().getField(getLinkparent_chile_columns()[i]).getType().equals(Date.class)	
					)
						
					{
						
					
						if((Date)getParent()
								.getValue(getLinkparentcolumns()[i])==null)
								{
							columnvalue += "null,";
								
								}
						else
						{
						columnvalue += "'"
							+ activeFormat.format((Date)getParent()
									.getValue(getLinkparentcolumns()[i]))
							+ "',";
						}
					}
					else
					{
					
						columnvalue += "'"
							+ getParent().getValue(getLinkparentcolumns()[i])
							+ "',";
					}
					
					
				}
				
			}
//			HashMap<String ,Object> hm = getDefaultvalue();
			
			GWT.log("str3="+modeldata.getProperties().keySet());
			//zgw 2010-3-11修改 添加默认数据的办法
			for(String str:modeldata.getProperties().keySet())
			{
				GWT.log("str="+str);
				//如果默认值在与主表关联的默认值里则跳出，保留和主表一致
				boolean bflag=false;
				if(getLinkparent_chile_columns()!=null)
				for(String str2:getLinkparent_chile_columns())
				{
					if(str.equals(str2))
					{
						bflag = true;
						break;
					}
				}
				if(bflag)
					continue;
				
				columnname +=str+ ",";
				if(modeldata.getProperties().get(str)!=null)
				GWT.log(str+"-"+modeldata.getProperties().get(str).getClass());
				if(modeldata.getProperties().get(str) instanceof ModelData)
				{
					Object o=((ModelData)modeldata.getProperties().get(str)).get("code");
					columnvalue += "'"+o+ "',";
				}
				//zgw 2010-6-27 添加类型判断
				else if(modeldata.getProperties().get(str) instanceof Long)
				{
					columnvalue += ""+modeldata.getProperties().get(str)+ ",";
				}
				else if(modeldata.getProperties().get(str) instanceof Double)
				{
					columnvalue += ""+modeldata.getProperties().get(str)+ ",";
				}
				else if(modeldata.getProperties().get(str) instanceof Date)
				{
					
					columnvalue += "'"+activeFormat.format((Date)modeldata.getProperties().get(str))+ "',";
				}
				else
				{
				columnvalue += "'"+modeldata.getProperties().get(str)+ "',";
				}
			}
			
			if (columnname.length() > 0) // 去尾巴字符
			{
				columnname = columnname.substring(0,
						columnname.length() - 1);
				columnvalue = columnvalue.substring(0,
						columnvalue.length() - 1);
			}

			//-------------------------old start
//			SendServlet ss = new SendServlet();
//			String icode = ss.getStringx("gwtbase/BaseServlet",
//					"Action=needicode&table=" + this.getTablename()
//							+ "&columnname=" + columnname + "&columnvalue="
//							+ columnvalue);
//			GWT.log("-" + icode + "-"+"Action=needicode&table=" + this.getTablename()
//					+ "&columnname=" + columnname + "&columnvalue="
//					+ columnvalue, null);
//			if (!(icode.equals("0") || icode.equals(""))) {
//				modeldata.set("icode", icode);
//
//				// 设置主键的原始值
//				if (modeldata instanceof BusiObject) {
//					((BusiObject) modeldata).put("icode", icode);
//				}
//				// 清除上面设置的insert状态，因为insert动作已经完成
//				if (modeldata instanceof BaseObject) {
//
//					((BaseObject) modeldata).clearBusistatus();
//				}
//
//				super.add(modeldata);
//
//				if (b) {
//					gotorow(this.indexOf(modeldata));
//				}
//				//触发 行增加
//				fireEvent(BaseStoreEvent.EventType.ROW_ADDED, BaseStoreEvent.BaseStoreRowAdded(this));
//
//			} else {
//				Window.alert("添加时发生错误。错误可能发生在数据出现了重复值！\n请不要同时添加多条记录。");
//			}
			
			//-----------------------old end
			//--------------------start
			
//			 StoreInfo si = new StoreInfo();
//				si.setTablename(this.getTablename());
//				HashMap hm = new HashMap();
//				hm.put("CODENAMEPARAMS", "{D:MMdd}{INC:3}{see}");
//				hm.put("CODENAMEFILTER", "1=1");
				
			 com.base.myproject.client.tools.GreetingServiceAsync greetingService = GWT
				.create(com.base.myproject.client.tools.GreetingService.class);
				greetingService.getIcodex(this.getStoreinfo(), columnname, columnvalue, getaddCallback(modeldata,b));
			//--------------------end
		} else {
			super.add(modeldata);

			if (b) {
				gotorow(this.indexOf(modeldata));
			}
			//触发 行增加
			fireEvent(BaseStoreEvent.EventType.ROW_ADDED, BaseStoreEvent.BaseStoreRowAdded(this));

		}
	}
	AsyncCallback<AddItem> ac ;
	private  AsyncCallback<AddItem> getaddCallback(final M modeldata,final boolean b)
	{
		ac = new AsyncCallback<AddItem> ()
		{

			@Override
			public void onFailure(Throwable caught) {
				MessageBox.alert("错误", "网络发生断裂，添加记录失败！", null);
				
			}

			@Override
			public void onSuccess(AddItem result) {
				_doafterAdd( modeldata,result, b);
				
			}
			
		};
		return ac;
	}
	private void _doafterAdd(M modeldata,AddItem ai,boolean b)
	{

		GWT.log(ai.getCodename());
		GWT.log(ai.getIcode());
		
		String icode = ai.getIcode();
		
		if (!(icode.equals("0") || icode.equals(""))) {
		modeldata.set("icode", icode);

		// 设置主键的原始值
		if (modeldata instanceof BusiObject) {
			((BusiObject) modeldata).put("icode", icode);
		}
		if(this.getStoreinfo().getBusiparmas()!=null && this.getStoreinfo().getBusiparmas().containsKey("CODENAME"))
		{
			
			modeldata.set(this.getStoreinfo().getBusiparmas().get("CODENAME"), ai.getCodename());
		}
		// 清除上面设置的insert状态，因为insert动作已经完成
		if (modeldata instanceof BaseObject) {

			((BaseObject) modeldata).clearBusistatus();
		}

		super.add(modeldata);

		if (b) {
			gotorow(this.indexOf(modeldata));
		}
		//触发 行增加
		fireEvent(BaseStoreEvent.EventType.ROW_ADDED, BaseStoreEvent.BaseStoreRowAdded(this));

	}
		
	
	}
	@Override
	public void add(List<? extends M> models) {

		if ((WRITE_ENABLE & basestorerwdstatus) != WRITE_ENABLE)
			return;
		for (int i = 0; i < models.size(); i++) {
			add(models.get(i));
		}

	}
	/**
	 * b=false 不马上在数据库添加数据，否则要添加数据到数据库
	 * @param models
	 * @param b
	 */
	public void add(List<? extends M> models,boolean b)
	{
		if ((WRITE_ENABLE & basestorerwdstatus) != WRITE_ENABLE)
			return;
		
		for (int i = 0; i < models.size(); i++) {
			
			add(models.get(i),b,b);
		}
	}

	/**
	 * 删除记录，要判断是否能够被删除
	 */
	public void remove(M model) {
		boolean b = true;
		for (RecordCompareInfo rci : this.getRecorddeletecomparell()) {
			rci.setModeldata(model);
			if (rci.Compare()) {
				b = true;
			} else {
				b = false;
				break;
			}

		}

		if (b || (DELETE_ENABLE & basestorerwdstatus) == DELETE_ENABLE) {

			if (model instanceof JDBCModelData) {
				((JDBCModelData) model).setStatus(JDBCModelData.ROW_DELETE);// 行插入状态
			}
			{
				setStatus(model, BaseObject.DELETE);
			}
			deletechilesql = "";
			deletechilesql = deleteChileTable(getChilestore());
		}
	}

	/**
	 * 删除子表 注意此删除不会发送删除事件
	 */

	String deleteChileTable(ArrayList<BaseStore> chile) {
		String str = "";
		for (BaseStore bs : chile) {
			if (bs.isParent()) {

				str += deleteChileTable(bs.getChilestore());
			} else {
				str += "delete " + bs.getTablename() + " where ";
				for (String stro : bs.getLinkparentcolumns()) {
					str += stro + "='" + bs.getParent().getValue(stro)
							+ "' and ";
				}
				str = str.substring(0, str.length() - 4) + ";";
			}
		}
		return str;
	}

	/**
	 *  保存单条记录
	 */
	public boolean trySave(final int rownum)
 {
		if(rownum<0)
		{
			MessageBox.alert("错误", "请选择要保存的行!", null);
			return false;
		}
		final java.util.Vector<String> v = new java.util.Vector<String>();
		v.addAll(_trySave(rownum));
		//2010-1-31 修改与服务器通讯办法
		com.base.myproject.client.tools.Command c1 = new com.base.myproject.client.tools.Command(){
			 public void Start()
				{
				 final com.base.myproject.client.tools.GreetingServiceAsync greetingService = GWT
					.create(com.base.myproject.client.tools.GreetingService.class);
			greetingService.saveBaseObject(v, null, new AsyncCallback<String>() {
				public void onFailure(Throwable caught) {
					Complete();
					MessageBox
							.alert(
									"提示",
									"保存失败。\n网络连接失败!请稍候保存数据！\n根据你使用网络的状况，你可能需要等待几分钟之后再尝试重新链接。\n如果你关闭窗口数据可能丢失。",
									null);

				}

				public void onSuccess(String result) {
					Complete();
					if (result.equals(SystemMessage.getMessage(4, 0))) {
						// 成功保存才设置状态，否则不设置，用户可以稍后保存
						_trySaveed(rownum);

						Info.display("", "保存成功", "");
					} else {
						MessageBox
								.alert(
										"提示",
										"保存失败。\n网络忙碌，与服务器交互失败!请稍候保存数据！\n根据你使用网络的状况，你可能需要等待几分钟之后再尝试重新链接。\n如果你关闭窗口数据可能丢失。",
										null);
					}

				}
			});
				 
				}
		};
		
		 CommandFactory.addCommand(c1);
		GWT.log(v.toString(), null);
		return false;
	}
	/**
	 * 获取单条记录保存的sql集合
	 * @param rownum
	 * @return
	 * 
	 */
	public  java.util.Vector<String> _trySave(int rownum) {
		fireEvent(BaseStoreEvent.EventType.SAVE_STARTED, BaseStoreEvent
				.BaseStoreSaveStart(basestorethis));

		
		java.util.Vector<String> v = new java.util.Vector<String>();
		//不需要保存，估计外部另外设置了保存的sql，处理特殊事务。默认保存sql取消。
		if(!isNeedsave())
		{
			//2010-4-15修改，保存某行就commit哪行
			this._commitChanges(this.getAt(rownum));
			return v;
			
		}
//		for (int i = 0; i < this.getCount(); i++) {

			if (this.getModels().get(rownum) instanceof BaseObject) {
				int status = ((BaseObject) this.getModels().get(rownum))
						.getBusistatus();
				if (status == BaseObject.NOTHING) {
				}
				else
				if ((status & BaseObject.DELETE) == BaseObject.DELETE) {
					String delete = ((BaseObject) this.getModels().get(rownum)).delete();
					if (delete != null)
						v.add(delete);
				} else if ((status & BaseObject.INSERT) == BaseObject.INSERT) {
					String insert = ((BaseObject) this.getModels().get(rownum)).insert();
					if ( insert!= null)
						v.add(insert);
				} else if ((status & BaseObject.UPDATE) == BaseObject.UPDATE) {
					String update = ((BaseObject) this.getModels().get(rownum)).update();
					if (update != null)
						v.add(update);
				}

			}
//		}
		if (this.getChilestore().size() > 0) {
			for (int i = 0; i < this.getChilestore().size(); i++) {
				v.addAll(this.getChilestore().get(i)._trySave());
			}
		}
		deletechilesql = null;

		return v;

	}
	/**
	 * 设置单条记录被保存后清除状态
	 * @param rownum
	 */
	public void _trySaveed(int rownum) {
		//2010-4-15修改，保存某行就commit哪行
	
		this._commitChanges(this.getAt(rownum));
		
		int row = 0;
			if (this.getModels().get(rownum) instanceof BaseObject) {
				int status = ((BaseObject) this.getModels().get(rownum))
						.getBusistatus();

				if (status == BaseObject.NOTHING) {
				} else if ((status & BaseObject.DELETE) == BaseObject.DELETE)

				{
					clearStatus(row);
					super.remove(getModels().get(rownum));
				} else {
					clearStatus(rownum);
					row++;
				}
			}

		if (this.getChilestore().size() > 0) {
			for (int i = 0; i < this.getChilestore().size(); i++) {
				this.getChilestore().get(i)._trySaveed();

			}
		}
		// 保存结束后触发事件
		fireEvent(BaseStoreEvent.EventType.SAVE_COMPLETE, BaseStoreEvent
				.BaseStoreSaveComplete(basestorethis));

	}
	/**
	 * 保存，全部保存
	 */
	public boolean trySave() {
		final java.util.Vector<String> v = new java.util.Vector<String>();
		//v.addAll(_trySave()); //zgw 2010-09-03 已经修改bug，用command方式下执行
		
		//2010-1-31 修改与服务器通讯办法
		com.base.myproject.client.tools.Command c1 = new com.base.myproject.client.tools.Command(){
			 public void Start()
				{
				 v.addAll(_trySave());
				
				 final com.base.myproject.client.tools.GreetingServiceAsync greetingService = GWT
					.create(com.base.myproject.client.tools.GreetingService.class);
			greetingService.saveBaseObject(v, null, new AsyncCallback<String>() {
				public void onFailure(Throwable caught) {
					Complete();
					MessageBox.alert("提示", "保存失败。\n网络连接失败!请稍候保存数据！\n根据你使用网络的状况，你可能需要等待几分钟之后再尝试重新链接。\n如果你关闭窗口数据可能丢失。", null);
					
				}

				public void onSuccess(String result) {
					Complete();
					if(result.equals(SystemMessage.getMessage(4, 0)))
					{
						//成功保存才设置状态，否则不设置，用户可以稍后保存
						_trySaveed();
						
						
						 Info.display("", "保存成功", "");  
					}
					else
					{
						MessageBox.alert("提示", "保存失败。\n网络忙碌，与服务器交互失败!请稍候保存数据！\n根据你使用网络的状况，你可能需要等待几分钟之后再尝试重新链接。\n如果你关闭窗口数据可能丢失。错误还可能是："+result, null);
					}
					

				}
			});
				}
		 };
		
		 CommandFactory.addCommand(c1);
		GWT.log(v.toString(), null);
		
		
		return false;
	}

	/**
	 * 保存后处理，清除状态标识，触发保存完成事件
	 */

	public void _trySaveed() {
		// for(int i=0;i<this.getCount();i++)
		int row = 0;
		while (row < getCount()) {

			if (this.getModels().get(row) instanceof BaseObject) {
				int status = ((BaseObject) this.getModels().get(row))
						.getBusistatus();

				if (status == BaseObject.NOTHING) {
					row++;
					continue;
				} else if ((status & BaseObject.DELETE) == BaseObject.DELETE)

				{
					clearStatus(row);
					super.remove(getModels().get(row));
				} else {
					clearStatus(row);
					row++;
				}
			}
		}

		if (this.getChilestore().size() > 0) {
			for (int i = 0; i < this.getChilestore().size(); i++) {
				this.getChilestore().get(i)._trySaveed();

			}
		}
		setIschanged(false);
		// 保存结束后触发事件
		fireEvent(BaseStoreEvent.EventType.SAVE_COMPLETE, BaseStoreEvent
				.BaseStoreSaveComplete(basestorethis));

	}

	/**
	 * 保存，根据BaseObject的状态表示形成可以提交给servlet的字符串，由服务器进行操作。 如果有子表则一起提交
	 * 
	 * @return
	 */
	public java.util.Vector<String> _trySave() {
		fireEvent(BaseStoreEvent.EventType.SAVE_STARTED, BaseStoreEvent
				.BaseStoreSaveStart(basestorethis));

		
		java.util.Vector<String> v = new java.util.Vector<String>();
//不需要保存，估计外部另外设置了保存的sql，处理特殊事务。默认保存sql取消。
		if(!isNeedsave())
		{
			this.commitChanges();
			return v;
		}
		for (int i = 0; i < this.getCount(); i++) {

			if (this.getModels().get(i) instanceof BaseObject) {
				int status = ((BaseObject) this.getModels().get(i))
						.getBusistatus();
				if (status == BaseObject.NOTHING) {
					continue;
				}
				if ((status & BaseObject.DELETE) == BaseObject.DELETE) {
					String delete = ((BaseObject) this.getModels().get(i)).delete();
					if (delete != null)
						v.add(delete);
				} else if ((status & BaseObject.INSERT) == BaseObject.INSERT) {
					String insert = ((BaseObject) this.getModels().get(i)).insert();
					if ( insert!= null)
						v.add(insert);
				} else if ((status & BaseObject.UPDATE) == BaseObject.UPDATE) {
					String update = ((BaseObject) this.getModels().get(i)).update();
					GWT.log("update in trysave="+update, null);
					if (update != null)
						v.add(update);
				}

			}
		}
		if (this.getChilestore().size() > 0) {
			for (int i = 0; i < this.getChilestore().size(); i++) {
				v.addAll(this.getChilestore().get(i)._trySave());
			}
		}
		this.commitChanges();
		deletechilesql = null;

		return v;

	}

	public void removeAll() {
		super.removeAll();

	}

	public void commitChanges() {
		super.commitChanges();
	}
	/**
	 * 单条记录被修改。
	 * @param m
	 */
	public void _commitChanges(M m) {
		  
		Record r = this.getRecord(m);
		r.commit(false);
		   
		    modified.remove(r);
		   
		  }
	public void reload() {
		
		
		loader = (BasePagingLoader) getBaseLoader(getType(), getStoreinfo());

		isinit = false;
		load();

	}

	
	/**
	 * 编辑结束后，如果编辑的是主表的主键，那么要一起更新子表的和主表关联的值
	 */
	protected void afterEdit(Record record) {
		// System.out.println("00000000002");
		ischanged = true;
		if (this.isParent()) {
			for (BaseStore bs : this.getChilestore()) {
				// zgw 2006-10-8 修改关联字段不一致的bug
				for (int k = 0; k < bs.getLinkparentcolumns().length; k++)
				{
					if (record.getChanges().containsKey(
							bs.getLinkparentcolumns()[k])) {
						for (int i = 0; i < bs.getCount(); i++) {
							bs.setValue(i, bs.getLinkparent_chile_columns()[k],
									record.getModel().get(
											bs.getLinkparentcolumns()[k]));
						}
					}
				}
			}
		}
		super.afterEdit(record);
	}

	public String[] getLinkparentcolumns() {
		return linkparentcolumns;
	}

	public void setLinkparentcolumns(String[] linkparentcolumns) {
		this.linkparentcolumns = linkparentcolumns;
	}

	/**
	 * @return the linkparent_chile_columns
	 */
	public String[] getLinkparent_chile_columns() {
		return linkparent_chile_columns;
	}

	/**
	 * 子表与主表关联字段，用于子表添加记录的时候保持和主表内容一致
	 * setLinkparentcolumns
	 * 与setLinkparent_chile_columns必须成对使用
	 * @param linkparent_chile_columns
	 *            the linkparent_chile_columns to set
	 */
	public void setLinkparent_chile_columns(String[] linkparent_chile_columns) {
		this.linkparent_chile_columns = linkparent_chile_columns;
	}

	// 设置行增加的时候的默认值
	public java.util.HashMap<String, Object> getDefaultvalue() {
		return defaultvalue;
	}

	public void setDefaultvalue(java.util.HashMap<String, Object> defaultvalue) {
		this.defaultvalue = defaultvalue;
	}

	/**
	 * 添加默认值,注意静态值和动态的值
	 * 
	 * @param key
	 * @param value
	 */
	public void addDefault(String key, Object value) {
		defaultvalue.put(key, value);

	}

	/**
	 * 获得数据的增删改的权限
	 * 
	 * @return
	 */
	public int getBasestorerwdstatus() {
		return basestorerwdstatus;
	}

	/**
	 * 设置数据的增删改的权限，直接影响到是否能增加
	 * 
	 * @param basestorerwdstatus
	 */
	public void setBasestorerwdstatus(int basestorerwdstatus) {
		this.basestorerwdstatus = basestorerwdstatus;
	}

	/**
	 * 记录增加的判断，如果判断结果为true那么就可以被增加，
	 * 
	 * @return
	 */
	public java.util.LinkedList<RecordCompareInfo> getRecordaddcomparell() {
		return recordaddcomparell;
	}

	public void setRecordaddcomparell(
			java.util.LinkedList<RecordCompareInfo> recordaddcomparell) {
		this.recordaddcomparell = recordaddcomparell;
	}

	/**
	 * 记录删除的判断，如果判断结果为true那么就可以被删除， 如果有多条判断记录那么要全部为真才能被删除
	 * 
	 * @return
	 */
	public java.util.LinkedList<RecordCompareInfo> getRecorddeletecomparell() {
		return recorddeletecomparell;
	}

	public void setRecorddeletecomparell(
			java.util.LinkedList<RecordCompareInfo> recorddeletecommparell) {
		this.recorddeletecomparell = recorddeletecommparell;
	}

	/**
	 * 自增字段，从服务器上取数的时候设置，客户端每次新增记录的时候在原值上加1
	 * 
	 * @return
	 */

	public String getAutoinc() {
		return autoinc;
	}

	/**
	 * 自增字段，从服务器上取数的时候设置，客户端每次新增记录的时候在原值上加1
	 * 
	 * @param autoinc
	 */
	public void setAutoinc(String autoinc) {
		this.autoinc = autoinc;
	}

	/**
	 * 服务器上返回的行总数，在分页显示的时候用到，否则无用。
	 * 
	 * @return
	 */
	public String getTotlerowcount() {
		return totlerowcount;
	}

	public void setTotlerowcount(String totlerowcount) {
		this.totlerowcount = totlerowcount;
	}

	/**
	 * ����������������� ����
	 * 
	 * @param servletflag
	 * @param url
	 * @param form
	 * @return
	 * @throws RequestException
	 */

	public boolean sendServlet(String servletflag, String url, String form)
			throws RequestException {

		setServletresponeString(null);
		RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, URL
				.encode(url));
		builder.setHeader("Content-Type",
				"application/x-www-form-urlencoded;charset=utf-8");
		builder.sendRequest(form, this);
		return true;
	}

	public boolean fireEvent(BaseStoreEvent.EventType eventType,
			BaseStoreEvent be) {
		if (listeners != null) {

			List<BaseStoreListener> list = listeners.get(eventType);
			if (list != null) {
				for (BaseStoreListener l : list) {

					l.BaseStoreEventHandle(be);
				}
			}

		}
		return true;
	}

	public void addBaseStoreListener(BaseStoreEvent.EventType eventType,
			BaseStoreListener listener) {
		if (listener == null)
			return;
		if (listeners == null) {
			listeners = new HashMap<BaseStoreEvent.EventType, List>();
		}
		List<BaseStoreListener> list = listeners.get(eventType);
		if (list == null) {
			list = new ArrayList<BaseStoreListener>();
			listeners.put(eventType, list);
		}

		if (!list.contains(listener)) {
			list.add(listener);
		}

	}

	public void removeBaseStoreListener(BaseStoreEvent.EventType eventType) {
		if (listeners == null)
			return;
		listeners.remove(eventType);
	}

	public void removeBaseStoreListener(BaseStoreEvent.EventType eventType,
			final BaseStoreListener listener) {
		if (listeners == null) {
			return;
		}

		List<Listener> list = listeners.get(eventType);
		if (list != null) {
			list.remove(listener);
			if (list.isEmpty()) {
				listeners.remove(eventType);
			}
		}

	}

	@Override
	public void onError(Request request, Throwable exception) {
		// TODO Auto-generated method stub
		System.out.println("error...");
	}

	@Override
	public void onResponseReceived(Request request, Response response) {
		// TODO Auto-generated method stub
		this.setServletresponeString(response.getText());
		Date date = new Date();

	}

	@Override
	public void BaseStoreEventHandle(BaseStoreEvent evt) {
		// TODO Auto-generated method stub

		if (evt.getEventType() == BaseStoreEvent.EventType.ROW_CHANGED) {

			if (this.isParent()) {
				for (int i = 0; i < chilestore.size(); i++) {
					if(this.getCurcowindex()==-1)
					{
						chilestore.get(i).removeAll();
						
						
						chilestore.get(i).fireEvent(BaseStoreEvent.EventType.LOAD_COMPLETE,
								BaseStoreEvent.BaseStoreLoadComplete(chilestore.get(i)));
						
						chilestore.get(i).fireEvent(BaseStoreEvent.EventType.ROW_CHANGED, BaseStoreEvent
								.BaseStoreRowChangedEvent(chilestore.get(i), -1));
						
						
					}
					else
					{
					String[] strarr = chilestore.get(i).getLinkparentcolumns();
					
					//zgw 2009-11-02 采用新的过滤方式
					Params p  =new Params();
					for(int j=0;j<strarr.length;j++)
					{
						Object value = evt.getBasestore().getValue(strarr[j]);
						if(value instanceof Date)
						{
							p.set(strarr[j], value==null?"null":DateTimeFormat.getFormat("yyyy-MM-dd HH:mm:ss").format((Date)value) );
						}
						else
						{
						p.set(strarr[j], value==null?"null":value );
						}
					}
					
					String sql = chilestore.get(i).getStoreinfo().getSql();
					GWT.log("chile load...", null);
					chilestore.get(i).setSqlnow( Format.substitute(sql, p));
					chilestore.get(i).getStoreinfo().setSql( Format.substitute(sql, p));
					chilestore.get(i).reload();
					chilestore.get(i).getStoreinfo().setSql(sql);
					
					}
				}
			}
		} else if (evt.getEventType() == BaseStoreEvent.EventType.SAVE_STARTED) {
			// 修改了保存的方式，由主表触发，所有子表都形成保存string，一起提交到服务程序，做一次性的保存
		}
	}

	@Override
	public void onBrowserEvent(Event event) {
		// TODO Auto-generated method stub

	}

	@SuppressWarnings("unchecked")
	public BasePagingLoader<PagingLoadResult<M>> getBaseLoader(ModelType type,
			final StoreInfo storeinfoloader) {
		
		
		Date date = new Date();
		
		RequestBuilder builder = new RequestBuilder(RequestBuilder.POST,
				"gwtbase/BaseServlet");
		
		builder.setHeader("Content-Type",
				"application/x-www-form-urlencoded;charset=utf-8");
		
		
		builder.setCallback(new RequestCallback() {

			@Override
			public void onError(Request request, Throwable exception) {
				// TODO Auto-generated method stub
				System.out.println("error.....");
			}

			@Override
			public void onResponseReceived(Request request, Response response) {
				// 
				Debug.printf("request="+request);
				Debug.printf("response="+response);
			}
		});
		HttpProxy proxy = new HttpProxy(builder);
		
		// need a loader, proxy, and reader
		XmlReader reader = new XmlReader(getType()) {

			protected ListLoadResult newLoadResult(Object loadConfig,
					List models) {
				PagingLoadConfig pagingConfig = (PagingLoadConfig) loadConfig;
				PagingLoadResult<ModelData> result = new BasePagingLoadResult<ModelData>(
						models, pagingConfig.getOffset(),Integer.parseInt( pagingConfig
								.getLimit()+""));

				return result;
			}

			@Override
			public ListLoadResult read(Object loadConfig, Object data) {
				// 日期型的格式
				
				DateTimeFormat activeFormat = DateTimeFormat
						.getFormat("yyyy-M-d H:mm:ss");

				GWT.log(data+"");
				if(data==null)
					return null;
				Document doc = XMLParser.parse((String) data);

				NodeList list = doc.getElementsByTagName(getType()
						.getRecordName());
				ArrayList<ModelData> records = new ArrayList<ModelData>();
				
			
				for (int i = 0; i < list.getLength(); i++) {
					Node node = list.item(i);
					Element elem = (Element) node;
					ModelData model = newModelInstance();
					for (int j = 0; j < getType().getFieldCount(); j++) {
						DataField field = getType().getField(j);
						Class c = getType().getField(j).getType();
						String map = field.getMap() != null ? field.getMap()
								: field.getName();
						String v = getValue(elem, map);
						/**
						 * 如果是BaseObject类或者其子类，这调用setNotFlag ，避免在初始化的时候也插入了标识
						 */
						if (model instanceof BaseObject) {
							Object o = null;
							if (c == null) {
								o = v;
							} else if (c.equals(Double.class)) {
								o = Double.parseDouble(v == null ? "0" : v);

							} else if (c.equals(Integer.class)) {

								o = Integer.parseInt(v == null ? "0" : v);
							} else if (c.equals(Long.class)) {
								o = Long.parseLong(v == null ? "0" : v);
							} else if (c.equals(Float.class)) {
								o = Float.parseFloat(v == null ? "0" : v);
							} else if (c.equals(Date.class)) {
								//bug,控制为何还要赋值？zgw 2010-06-25
								//2010-6-25 修改
								if(v!=null)
								{
									//bug zgw 2010 -8-17
									v = v.substring(0, 19);
									o = activeFormat.parse(v);

								}
							} 
							else if(c.equals(Boolean.class))
							{
							
								if(v==null || v.equals("0"))
								{
									o = Boolean.FALSE;
								}
								else
								{
								o=Boolean.TRUE;
								}
							}
							else if (c.equals(String.class)) {
								o = v;
							} else {
								throw new java.lang.RuntimeException("不支持的数据类型"
										+ c);
							}
							((BusiObject) model).setNotFlag(field.getName(), o);
						} else {
							model.set(field.getName(), v);
						}
					}
					/**
					 * 如果是BusiObject 那么要设置主键的原始值，方便增删改操作
					 */
					if (model instanceof BusiObject) {

						if (((BusiObject) model).getStoreinfo() == null)

						{
							GWT.log("没有设置主键，不能保存", null);
						} else {
							String[] keyarray = ((BusiObject) model)
									.getStoreinfo().getKeyname();
							if (keyarray != null) {
								for (int k = 0; k < keyarray.length; k++) {
									((BusiObject) model).put(keyarray[k],
											getValue(elem, keyarray[k]));
								}
							}
						}
					}
					records.add(model);
				}

				int totalCount = records.size();

				Node root = doc.getElementsByTagName(getType().getRoot()).item(
						0);
				if (root != null && getType().getTotalName() != null) {
					Node totalNode = root.getAttributes().getNamedItem(
							getType().getTotalName());
					if (totalNode != null) {
						String sTot = totalNode.getNodeValue();
						totalCount = Integer.parseInt(sTot);
					}
				}
				// 获得自曾字段的值

				if (root != null) {
					Node totalNode = root.getAttributes().getNamedItem(
							"autoinc");
					if (totalNode != null) {
						autoinc = totalNode.getNodeValue();
					}
				}
				ListLoadResult result = newLoadResult(loadConfig, records);
				if (result instanceof PagingLoadResult) {
					PagingLoadResult r = (PagingLoadResult) result;
					r.setTotalLength(totalCount);
					setTotlerowcount(totalCount + "");
				}
			
				return result;
			}

			protected ModelData newModelInstance() {
				if (mode == 1) {
					return new BusiObject(BaseStore.this.storeinfo);
				}
				else if(mode == 2)
				{
					return new CcodeBusiObject(BaseStore.this.storeinfo);
				}
				return super.newModelInstance();
			}
		};

		BasePagingLoader<PagingLoadResult<M>> loader = new BasePagingLoader<PagingLoadResult<M>>(
				proxy, reader)
				{
				protected Object prepareLoadConfig(Object config) {
					config = super.prepareLoadConfig(config);
					 PagingLoadConfig pagingConfig = (PagingLoadConfig) config;
					 for(String str:storeinfoloader.getstoreinfoht().keySet())
					 {
						 pagingConfig.set(str, storeinfoloader.getstoreinfoht().get(str));
					 }
					 pagingConfig.set("Action","Loaddata");
					return config;
				}
				};
		
		return loader;
	}

	public ListLoader<? extends ListLoadResult<M>> getLoader() {
		return loader;
	}

	// 在combox时候有用，设置为null，就不会从远程服务器取数，在其他地方尽量不要使用
	public void setLoader(ListLoader loader) {
		this.loader = loader;

	}

	public int getCount() {

		return super.getCount();
	}

	/**
	 * @return the ischanged
	 */
	public boolean isIschanged() {
		return ischanged;
	}

	/**
	 * @param ischanged
	 *            the ischanged to set
	 */
	public void setIschanged(boolean ischanged) {
		this.ischanged = ischanged;
	}

	public boolean isNeedsave() {
		return needsave;
	}

	/**
	 * 设置是否需要保存，默认true需要保存，负责trysave的时候不需要组织sql提交到servlet
	 * @param needsave
	 */
	
	public void setNeedsave(boolean needsave) {
		this.needsave = needsave;
	}
/**
 * 当前执行的sql，对于刷新当前的数据表有用。子表可以通过此语句单独刷新
 * 前提是曾经进行1此刷新。否则为null；
 *  String sql = dstore.getStoreinfo().getSql();
							 dstore.getStoreinfo().setSql(dstore.getSqlnow());
							 dstore.reload();
							 dstore.getStoreinfo().setSql(sql);
							
 * @return
 */

	public String getSqlnow() {
		return sqlnow;
	}

public void setSqlnow(String sqlnow) {
	this.sqlnow = sqlnow;
}

public boolean isNeedtodeelroweditable() {
	return needtodeelroweditable;
}

public void setNeedtodeelroweditable(boolean needtodeelroweditable) {
	this.needtodeelroweditable = needtodeelroweditable;
}

public ArrayList<Editdisable> getEditdisablelist() {
	return editdisablelist;
}

public void setEditdisablelist(ArrayList<Editdisable> editdisablelist) {
	this.editdisablelist = editdisablelist;
	if(editdisablelist!=null)
	{
		setNeedtodeelroweditable(true);
	}
}
public void addEditdisableItem(Editdisable editable)
{
	this.editdisablelist.add(editable);
	setNeedtodeelroweditable(true);
}

public static enum EditDisableType {
    
    IN,
    EQUALS,
    LIKE;
  }


}
